# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # AuthenticatedSystem must be included for RoleRequirement, and is provided by installing acts_as_authenticates and running 'script/generate authenticated account user'.
  include AuthenticatedSystem
  # You can move this into a different controller, if you wish.  This module gives you the require_role helpers, and others.
  include RoleRequirement


  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_ipm_session_id'
  
  before_filter :login_from_cookie
  
  before_filter :login_required, :except => [:login, :signup]

   
   def sort_helper(param, items={})
     if param
       items.each do |item|
         if param == "#{item}"
           return "#{item}"
         elsif param == "#{item}_reverse"
           return "#{item} DESC"
         end
       end
     end
   end
   
   
   def list_type_helper(list_type, conditions)

     states = []
     conditions_text = []
     
     if !Ticket.default_states[list_type].nil?
       states << list_type
     else
       if list_type == 'all'
         states << 'unassigned'
         states << 'in_treatment'
         states << 'finished'
         states << 'unrepairable'
         states << 'wont_fix'
         states << 'approved'
         states << 'not_approved'
         states << 'duplicate'
       elsif list_type == 'active'
         states << 'unassigned'    
         states << 'in_treatment'   
         states << 'not_approved'
       elsif list_type == 'closed'
        states << 'finished'
        states << 'approved'
        states << 'unrepairable'
        states << 'wont_fix'
        states << 'duplicate'
       elsif list_type == 'invalid' 
        states << 'unrepairable'
        states << 'wont_fix'
        states << 'duplicate'
         
       end
       
     end

      states.each do |state|
         conditions_text << "status = " + Ticket.default_states[state].to_s
       end
       
      if not conditions.nil?
       conditions[0] = conditions[0] + " AND ("+conditions_text.join(" OR ")+")"
      else
       conditions = "("+conditions_text.join(" OR ")+")"
      end
     return conditions

   end
   
   def strip_html(s)
     return s.to_s.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')
   end
   
   def ae_some_html(s)
       # converting newlines
       s.gsub!(/\r\n?/, "\n")

       # escaping HTML to entities
       s = s.to_s.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')

       # blockquote tag support
       s.gsub!(/\n?&lt;blockquote&gt;\n*(.+?)\n*&lt;\/blockquote&gt;/im, "<blockquote>\\1</blockquote>")

       # other tags: b, i, em, strong, u
       %w(b i em strong u).each { |x|
            s.gsub!(Regexp.new('&lt;(' + x + ')&gt;(.+?)&lt;/('+x+')&gt;',
                    Regexp::MULTILINE|Regexp::IGNORECASE), 
                    "<\\1>\\2</\\1>")
           }

       # A tag support
       # href="" attribute auto-adds http://
       s = s.gsub(/&lt;a.+?href\s*=\s*['"](.+?)["'].*?&gt;(.+?)&lt;\/a&gt;/im) { |x|
               '<a href="' + ($1.index('://') ? $1 : 'http://'+$1) + "\">" + $2 + "</a>"
             }

       # replacing newlines to <br> ans <p> tags
       # wrapping text into paragraph
       s = "<p>" + s.gsub(/\n\n+/, "</p>\n\n<p>").
               gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') + "</p>"

       s      
   end
   
   # TODO misschien ergens anders neerzetten?
   def search_helper(query, search_fields={})
     conditions_text = []
     conditions_params = []

     search_fields.each do |search_field|
       conditions_text << "#{search_field} LIKE ?"
       conditions_params << "%#{query}%"
     end

     conditions_text.empty? ? nil : ["("+conditions_text.join(" OR ")+")", *conditions_params]
   end
   
   def tag_search_helper(query, search_fields={})
      conditions_text = []
      conditions_params = []

      search_fields.each do |search_field|
        conditions_text << "#{search_field} LIKE '%#{query}%'"
      end

      conditions_text.empty? ? nil : ["("+conditions_text.join(" OR ")+")", *conditions_params]
    end
   
   
end
